<template>
  <div class="ai-reading">
    <!-- 加载遮罩 -->
    <div class="loading-overlay" v-if="loading">
      <div class="loading-content">
        <div class="spinner-border text-primary spinner" role="status"></div>
        <div>正在生成中，请稍候...</div>
        <small class="text-muted">预计需要15秒</small>
      </div>
    </div>

    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/english/ai-exercise" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">AI生成的阅读理解</h5>
      <span class="ai-badge">
        <i class="bi bi-robot"></i> AI生成
      </span>
    </div>

    <!-- 目标词汇展示 -->
    <div class="vocab-list">
      <div class="mb-2">使用的目标词汇：</div>
      <span v-for="vocab in vocabList" 
        :key="vocab.word" 
        class="vocab-item"
        @click="showVocabDetail(vocab)"
      >{{ vocab.word }}</span>
    </div>

    <!-- 添加单词详情 Modal -->
    <div class="modal fade" id="vocabDetailModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">单词详情</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body" v-if="selectedVocab">
            <div class="vocab-detail-card">
              <div class="word-header">
                <h3 class="word">{{ selectedVocab.word }}</h3>
              </div>
              <div class="definition-section">
                <div class="section-label">英文释义：</div>
                <div class="english-definition">{{ selectedVocab.english_definition }}</div>
              </div>
              <div class="translation-section">
                <div class="section-label">中文翻译：</div>
                <div class="english-definition">{{ selectedVocab.chinese_translation }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 阅读内容 -->
    <div class="reading-content">
      <div class="passage-header" v-if="showFullAnalysis">
        <h4 class="text-center mb-4">
          <div class="english-title">{{ title.english }}</div>
          <div class="chinese-title">{{ title.chinese }}</div>
        </h4>
      </div>
      <div class="paragraph" v-for="(para, index) in paragraphs" :key="index">
        <div class="english-text" v-html="highlightVocabs(para)"></div>
        <div class="chinese-text" v-if="showFullAnalysis">{{ translations[index] }}</div>
      </div>
    </div>

    <!-- 题目部分 -->
    <div class="question-section">
      <div class="question" v-for="(question, index) in questions" :key="index">
        <p>
          <strong>{{ index + 1 }}. {{ question.text }}</strong>
          <div class="question-chinese" v-if="showFullAnalysis">{{ question.chinese }}</div>
        </p>
        <a href="#" 
          v-for="option in question.options" 
          :key="option.id"
          class="option"
          :class="{
            'selected': option.id === question.selectedOption,
            'correct': showFullAnalysis && option.id === question.correctAnswer,
            'incorrect': showFullAnalysis && option.id === question.selectedOption && option.id !== question.correctAnswer
          }"
          @click.prevent="selectOption(question, option.id)"
        >
          {{ option.id }}. {{ option.text }}
          <div class="option-chinese" v-if="showFullAnalysis">{{ option.chinese }}</div>
        </a>
        
        <!-- 答案解析部分 -->
        <div class="answer-analysis" v-if="showFullAnalysis">
          <div class="analysis-content">
            <div class="correct-answer">
              <span class="label">正确答案：</span>
              <span class="answer">{{ question.correctAnswer }}</span>
            </div>
            <div class="explanation">
              <div class="english">{{ question.explanation.english }}</div>
              <div class="chinese">{{ question.explanation.chinese }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools position-fixed bottom-0 w-100 bg-white p-3">
      <div class="d-flex justify-content-between align-items-center">
        <button class="regenerate-btn" 
          @click="regenerateContent"
          :disabled="isRegenerating"
        >
          <i class="bi bi-arrow-clockwise"></i>
          {{ isRegenerating ? '生成中...' : '重新生成' }}
        </button>
        <button 
          class="btn btn-primary" 
          @click="viewAnalysis"
          :disabled="!hasAllAnswers"
        >
          查看答案解析
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/router/http'
import * as bootstrap from 'bootstrap'

export default {
  name: 'AIReadingView',
  
  data() {
    return {
      isRegenerating: false,
      vocabList: [],
      paragraphs: [],
      questions: [],
      loading: false,
      selectedVocab: null,
      vocabCount: 10,
      vocabModal: null,
      isFirstLoad: true,
      isGenerating: false,
      translations: [],
      passageAnalysis: {
        english: '',
        chinese: ''
      },
      showFullAnalysis: false,
      title: {
        english: '',
        chinese: ''
      }
    }
  },

  computed: {
    // 检查是否所有题目都已作答
    hasAllAnswers() {
      return this.questions.every(q => q.selectedOption !== null)
    }
  },

  async created() {
    if (this.isFirstLoad) {
      this.loading = true
      try {
        this.vocabCount = parseInt(this.$route.query.vocabCount) || 10
        await this.generateReading()
        this.isFirstLoad = false
      } catch (error) {
        console.error('生成练习失败:', error)
        alert(error.message || '生成练习失败，请重试')
        this.$router.back()
      } finally {
        this.loading = false
      }
    }
  },

  mounted() {
    // 初始化 Modal
    this.vocabModal = new bootstrap.Modal(document.getElementById('vocabDetailModal'))
  },

  methods: {
    async generateReading() {
      // 防止重复请求
      if (this.isGenerating) {
        return
      }
      
      this.isGenerating = true
      
      try {
        const vocabResponse = await http.get('/student/vocabularyList/select')
        
        if (vocabResponse.data.code !== 1) {
          throw new Error(vocabResponse.data.message || '获取生词列表失败')
        }
        
        const selectedVocabs = this.getRandomVocabs(vocabResponse.data.response, this.vocabCount)
        
        const response = await http.post('/student/ai/forward/english/generate_reading', {
          words: selectedVocabs
        })
        
        if (response.data.code !== 1) {
          throw new Error(response.data.message || 'Failed to generate exercise')
        }
        
        const readingQuiz = response.data.response.reading_quiz
        
        // 设置标题（如果API提供）
        this.title = {
          english: readingQuiz.passage.title?.english || '',
          chinese: readingQuiz.passage.title?.chinese || ''
        }
        
        // 设置段落内容和翻译
        this.paragraphs = [readingQuiz.passage.english]
        this.translations = [readingQuiz.passage.chinese]
        
        // 处理问题数据
        this.questions = readingQuiz.questions.map(q => ({
          text: q.question.english,
          chinese: q.question.chinese,
          options: Object.entries(q.options).map(([id, option]) => ({
            id,
            text: option.english,
            chinese: option.chinese
          })),
          selectedOption: null,
          correctAnswer: q.correct_answer,
          explanation: {
            english: q.explanation.english,
            chinese: q.explanation.chinese
          },
          showAnswer: false
        }))

        // 处理词汇列表
        this.vocabList = readingQuiz.vocabulary.map(vocab => ({
          word: vocab.word,
          english_definition: vocab.definition,
          chinese_translation: vocab.usage
        }))

        // 设置文章解析（如果 API 没有提供这个字段，我们可以暂时留空）
        this.passageAnalysis = {
          english: readingQuiz.passage.english || '',
          chinese: readingQuiz.passage.chinese || ''
        }
        
      } catch (error) {
        throw error
      } finally {
        this.isGenerating = false
      }
    },

    highlightVocabs(text) {
      let highlightedText = text
      this.vocabList.forEach(vocab => {
        const regex = new RegExp(vocab.word, 'gi')
        highlightedText = highlightedText.replace(
          regex, 
          `<span class="target-vocab">${vocab.word}</span>`
        )
      })
      return highlightedText
    },

    selectOption(question, optionId) {
      if (question.selectedOption !== null) {
        return // 如果已经选择了答案，不允许再次选择
      }
      question.selectedOption = optionId
    },

    async regenerateContent() {
      if (this.isRegenerating || this.isGenerating) {
        return
      }

      this.isRegenerating = true
      this.loading = true
      
      try {
        await this.generateReading()
        // 重置所有选项
        this.questions.forEach(q => q.selectedOption = null)
      } catch (error) {
        console.error('重新生成失败:', error)
        alert(error.message || '重新生成失败，请重试')
      } finally {
        this.isRegenerating = false
        this.loading = false
      }
    },

    getRandomVocabs(vocabList, count) {
      const unmastered = vocabList.filter(vocab => vocab.situation === '未掌握')
      
      if (unmastered.length <= count) {
        return unmastered.map(vocab => vocab.newWord)
      }
      
      const shuffled = [...unmastered].sort(() => 0.5 - Math.random())
      return shuffled.slice(0, count).map(vocab => vocab.newWord)
    },

    showVocabDetail(vocab) {
      this.selectedVocab = vocab
      this.vocabModal.show()
    },

    viewAnalysis() {
      if (!this.hasAllAnswers) {
        alert('请完成所有题目后再查看解析')
        return
      }
      
      this.showFullAnalysis = true

      // 滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }
  }
}
</script>

<style scoped>
.ai-reading {
  background-color: #f0f9f9;
  min-height: 100vh;
  padding-bottom: 80px;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.ai-badge {
  background: linear-gradient(45deg, #40e0d0, #3bcdc0);
  color: white;
  padding: 4px 12px;
  border-radius: 15px;
  font-size: 0.8rem;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.vocab-list {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin: 15px;
}

.vocab-item {
  display: inline-block;
  background: white;
  padding: 4px 12px;
  border-radius: 15px;
  margin: 4px;
  font-size: 0.9rem;
  border: 1px solid #eee;
}

.reading-content {
  background: white;
  padding: 20px;
  line-height: 1.8;
}

:deep(.target-vocab) {
  background: rgba(64, 224, 208, 0.1);
  border-bottom: 2px solid #40e0d0;
  padding: 0 2px;
}

.question-section {
  background: white;
  padding: 20px;
}

.question {
  margin-bottom: 25px;
}

.question p {
  font-weight: 500;
  color: #333;
  margin-bottom: 15px;
}

.option {
  display: block;
  width: 100%;
  padding: 12px 15px;
  margin-bottom: 10px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  color: #333;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  padding-left: 3em;
}

.option:hover {
  background: #e9ecef;
  color: #333;
  transform: translateX(5px);
  text-decoration: none;
}

.option.selected {
  background: #40e0d0;
  color: white;
  border-color: #40e0d0;
}

.option.correct {
  background: #4caf50;
  color: white;
  border-color: #4caf50;
}

.option.incorrect {
  background: #f44336;
  color: white;
  border-color: #f44336;
}

.bottom-tools {
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.regenerate-btn {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.regenerate-btn:hover:not(:disabled) {
  background: #3bcdc0;
}

.regenerate-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  text-align: center;
}

.spinner {
  width: 3rem;
  height: 3rem;
  margin-bottom: 1rem;
}

.answer-analysis {
  margin-top: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #40e0d0;
}

.analysis-content {
  font-size: 0.95rem;
}

.correct-answer {
  margin-bottom: 10px;
}

.correct-answer .label {
  color: #666;
  margin-right: 5px;
}

.correct-answer .answer {
  color: #4caf50;
  font-weight: bold;
}

.explanation {
  color: #666;
}

.explanation .english {
  margin-bottom: 5px;
}

.explanation .chinese {
  color: #888;
  font-size: 0.9em;
}

.chinese-text {
  color: #666;
  font-size: 0.95rem;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

.passage-analysis {
  background: #f8f9fa;
  padding: 20px;
  margin-bottom: 30px;
  border-radius: 8px;
  border-left: 4px solid #40e0d0;
}

.analysis-title {
  color: #333;
  margin-bottom: 15px;
  font-weight: 500;
}

.passage-analysis .analysis-content {
  font-size: 0.95rem;
}

.passage-analysis .english {
  color: #333;
  margin-bottom: 10px;
}

.passage-analysis .chinese {
  color: #666;
}

.question-chinese {
  color: #666;
  font-size: 0.9rem;
  margin-top: 5px;
}

.option-chinese {
  color: #666;
  font-size: 0.9rem;
  margin-top: 5px;
  border-top: 1px dashed #eee;
  padding-top: 5px;
}

.option {
  /* ... 其他样式保持不变 ... */
  display: block;
  padding: 12px 15px;
}

.option.correct .option-chinese,
.option.incorrect .option-chinese {
  color: rgba(255, 255, 255, 0.8);
  border-top-color: rgba(255, 255, 255, 0.2);
}

.passage-header {
  margin-bottom: 20px;
}

.english-title {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 5px;
}

.chinese-title {
  font-size: 1rem;
  color: #666;
}
</style> 